package com.hefan.live.dao;

import com.cat.tiger.util.CollectionUtils;
import com.google.common.collect.Lists;
import com.hefan.common.orm.dao.CommonDaoImpl;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.bean.LivingRoomInfoVo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by nigle on 2016/9/26.
 */
@Repository
public class LiveLogDao extends CommonDaoImpl {

    private static String TABLE_NAME = "live_log";

    @Resource
    JdbcTemplate jdbcTemplate;

    public LiveLog getLiveLogByUuid(String liveUuid){
        String sql = "select ll.abnormal_end,ll.chat_room_id,ll.display_graph,ll.live_img," +
                "ll.end_time,ll.false_ticket_count,ll.handle_status,ll.id,ll.live_length," +
                "ll.live_name,ll.live_url,ll.live_uuid,ll.location,ll.opt_user,ll.pull_url," +
                "ll.start_time,ll.ticket_count,ll.user_id,ll.valid_live_length,ll.watch_num," +
                "ll.is_vip_live isVipLive, ll.is_show isShow, ll.is_landscape isLandscape " +
                " from live_log ll where ll.live_uuid = ? ";
        List<LiveLog> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<LiveLog>(LiveLog.class),liveUuid);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }
    public LiveLog getLiveLogByUserId(String roomId) {
        String sql = "select ll.abnormal_end,ll.chat_room_id,ll.display_graph,ll.live_img," +
                "ll.end_time,ll.false_ticket_count,ll.handle_status,ll.id,ll.live_length," +
                "ll.live_name,ll.live_url,ll.live_uuid,ll.location,ll.opt_user,ll.pull_url," +
                "ll.start_time,ll.ticket_count,ll.user_id,ll.valid_live_length,ll.watch_num," +
                "ll.is_vip_live isVipLive, ll.is_show isShow, ll.is_landscape isLandscape " +
                " from live_log ll where ll.chat_room_id = ? order by start_time DESC limit 1";
        List<LiveLog> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<LiveLog>(LiveLog.class), roomId);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }
    /**
     * 开播时闭环liveLog表
     * @param userId
     * @return
     */
    public List<LiveLog> getLiveLogListByUserId(String userId) {
        String sql = "select ll.abnormal_end,ll.chat_room_id,ll.display_graph," +
                "ll.end_time,ll.false_ticket_count,ll.handle_status,ll.id,ll.live_length," +
                "ll.live_name,ll.live_url,ll.live_uuid,ll.location,ll.opt_user,ll.pull_url," +
                "ll.start_time,ll.ticket_count,ll.user_id,ll.valid_live_length,ll.watch_num," +
                "ll.is_vip_live isVipLive, ll.is_show isShow, ll.is_landscape isLandscape " +
                " from live_log ll where ll.user_id = ? and ll.end_time is null ORDER BY ll.start_time desc";
        List<LiveLog> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<LiveLog>(LiveLog.class),userId);
        return  CollectionUtils.isNotEmpty(list) ? list : new ArrayList<>();
    }


    /**
     * 开播时初始化LiveLog
     * @param liveLog
     * @return
     */
    public int insterLiveLog(LiveLog liveLog){
        String sql = "insert IGNORE into live_log ( user_id,chat_room_id,live_uuid,pull_url,live_url,location,live_name,display_graph,live_img,is_vip_live,is_show,is_landscape ) VALUES ( ?,?,?,?,?,?,?,?,?,?,?,? )";
        Object[] o = new Object[]{liveLog.getUserId(),liveLog.getChatRoomId(),liveLog.getLiveUuid(),liveLog.getPullUrl(),
                liveLog.getLiveUrl(),liveLog.getLocation(),liveLog.getLiveName(),liveLog.getDisplayGraph(),
                liveLog.getLiveImg(),liveLog.getIsVipLive(),liveLog.getIsShow(),liveLog.getIsLandscape()};
        logger.info("VIP-LIVELOG-"+sql);
        return jdbcTemplate.update(sql, o);
    }

    /**
     * 下单后更新直播盒饭收入（包含虚拟）
     * @param liveLog
     * @return
     */
    public int updateLiveLogForRebalance(LiveLog liveLog){
        String sql = "update live_log ll set ll.ticket_count = ll.ticket_count + ? ,ll.false_ticket_count = ll.false_ticket_count + ? where ll.user_id = ? and ll.live_uuid = ?";
        Object[] o = new Object[]{liveLog.getTicketCount(),liveLog.getFalseTicketCount(), liveLog.getUserId(),liveLog.getLiveUuid()};
        return jdbcTemplate.update(sql,o);
    }

    /**
     * 主播结束直播后闭环数据
     * @param liveLog
     * @return
     */
    public int updateLiveLogByEnd(LiveLog liveLog) {
        Timestamp now = new Timestamp(new Date().getTime());
        String sql = "update live_log ll set ll.end_time = ? , ll.live_length = ? , ll.valid_live_length = ? ,ll.abnormal_end = ? ,ll.opt_user = ? , ll.watch_num = ? ,ll.update_time = ? where ll.live_uuid = ?";
        Object[] o = new Object[]{liveLog.getEndTime(),liveLog.getLiveLength(),liveLog.getValidLiveLength(),liveLog.getAbnormal_end(),liveLog.getOptUser(),liveLog.getWatchNum(),now,liveLog.getLiveUuid()};
        return jdbcTemplate.update(sql,o);
    }

    /**
     * 用户进出直播间时更新观看人数
     * @return
     */
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
	public int changeWatchNum(String liveUuid, int chatRoomId, int addNum) {
		String sql = "update live_log set watch_num = watch_num + ? where chat_room_id = ? and live_uuid = ? and end_time IS NULL";
		Object[] o = new Object[] { addNum, chatRoomId, liveUuid };
		return jdbcTemplate.update(sql, o);
	}

    /**
     * 李腾
     */
    public LiveLog getLiveLogByLiveTime(String roomId, String liveTime){
        String sql = "select ll.abnormal_end,ll.chat_room_id,ll.display_graph," +
                "ll.end_time,ll.false_ticket_count,ll.handle_status,ll.id,ll.live_length," +
                "ll.live_name,ll.live_url,ll.live_uuid,ll.location,ll.opt_user,ll.pull_url," +
                "ll.start_time,ll.ticket_count,ll.user_id,ll.valid_live_length,ll.watch_num," +
                "ll.is_vip_live isVipLive, ll.is_show isShow, ll.is_landscape isLandscape " +
                " from live_log ll where ll.chat_room_id =?  and ? BETWEEN start_time AND IFNULL(end_time,'3000-01-01 00:00:00')";
        Object[] obj = new Object[]{roomId,liveTime};
        List<LiveLog> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<LiveLog>(LiveLog.class),obj);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    /**
     * 查询正在直播的liveLog
     * @return
     */
    public LiveLog getLivingLiveLog(String userId) {
        String sql = "select ll.abnormal_end,ll.chat_room_id,ll.display_graph," +
                "ll.end_time,ll.false_ticket_count,ll.handle_status,ll.id,ll.live_length," +
                "ll.live_name,ll.live_url,ll.live_uuid,ll.location,ll.opt_user,ll.pull_url," +
                "ll.start_time,ll.ticket_count,ll.user_id,ll.valid_live_length,ll.watch_num," +
                "ll.is_vip_live isVipLive, ll.is_show isShow, ll.is_landscape isLandscape " +
                " from live_log ll where ll.user_id = ? ORDER BY ll.start_time desc LIMIT 1 ";
        List<LiveLog> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<LiveLog>(LiveLog.class),userId);
        return CollectionUtils.isNotEmpty(list)?list.get(0):null;
    }

    /**
     * 查询未关闭的直播liveLog
     *
     * @return
     */
    public List<LiveLog> getLivingLiveLogList() {
        String sql = "select id, user_id userId, chat_room_id chatRoomId, live_name liveName, live_uuid liveUuid, start_time startTime, " +
                " end_time endTime, is_vip_live isVipLive, is_show isShow, is_landscape isLandscape from live_log where end_time is null ";
        List<LiveLog> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<LiveLog>(LiveLog.class));
        return CollectionUtils.isNotEmpty(list) ? list : new ArrayList<LiveLog>();
    }

  /**
   * 更改直播名称和描述
   */
  public int updateLiveLogForMonitor(String liveImg, String liveName, String liveUuid) {
    Timestamp now = new Timestamp(new Date().getTime());
    String sql = "update live_log ll set ll.live_name = ?, ll.live_img = ?, ll.update_time = ? where ll.live_uuid = ?";
    Object[] o = new Object[]{liveName, liveImg, now, liveUuid};
    return jdbcTemplate.update(sql,o);
  }

    /**
     * 更新VIP直播间状态
     *
     * @param livingRoomInfoVo
     * @return
     */
    public int updateVIPLiveLogStatus(LivingRoomInfoVo livingRoomInfoVo) {
        String sql = "update live_log ll set ll.is_show = ?  where ll.live_uuid = ?";
        Object[] o = new Object[]{livingRoomInfoVo.getIsShow(), livingRoomInfoVo.getLiveUuid()};
        return jdbcTemplate.update(sql, o);
    }

  public List<LiveLog> getLiveLogByEndTime(String startTime, String endTime) {
    String sql = "select ll.live_uuid as liveUuid,ll.user_id as userId from live_log ll where ll.end_time BETWEEN ? AND ? ";
    List<LiveLog> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<LiveLog>(LiveLog.class), new Object[] { startTime, endTime });
    return CollectionUtils.isNotEmpty(list) ? list : Lists.newArrayList();
  }
}


